package com.osfw.framework.config;


import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.temp.SaTempUtil;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.osfw.framework.constants.Constants;
import com.osfw.framework.constants.SaTokenConstants;
import com.osfw.framework.interceptor.RepeatSubmitInterceptor;
import com.osfw.framework.utils.CookieUtils;
import com.osfw.framework.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author 跨域访问配置
 */
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {

    @Autowired
    private RepeatSubmitInterceptor repeatSubmitInterceptor;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** swagger配置 */
        registry.addResourceHandler("/swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
    }

    // 注册Sa-Token的注解拦截器，打开注解式鉴权功能
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // token 校验
        registry.addInterceptor(new SaInterceptor(handler -> {
            // 登录连接拦截临时token校验
            SaRouter.match("/osfw", "/osfw/dispatch", "/osfw/login", "/osfw/captcha/checkCaptchaCode", "/osfw/doLogin", "/osfw/framework/login/**", "/osfw/framework/login2/**")
                    // 排除指定静态资源文件
                    .notMatch("/osfw/favicon.ico", "/osfw/framework/**/libs/jquery/**", "/osfw/framework/**/libs/blockUI/**", "/osfw/framework/**/libs/modernizr/**", "/osfw/framework/**/libs/amazeui/**", "/osfw/framework/base/common/**", "/osfw/framework/error/**", "/osfw/**/libs/sm2/sm2.js", "/osfw/framework/**/libs/base64/jquery.base64.js", "/osfw/framework/login/vcode/**", "/osfw/framework/login/eraser/**")
                    .check(r -> {
                        if (!StpUtil.isLogin() && Global.isSaTempEnabled()) {
                            String token = CookieUtils.getCookie(ServletUtils.getRequest(), Constants.TEMP_TOKEN_NAME);
                            if (token != null) {
                                if(SaTempUtil.getTimeout(token) <= 0) {
                                    throw NotLoginException.newInstance("login", SaTokenConstants.TEMP_TOKEN_TIMEOUT, SaTokenConstants.TEMP_TOKEN_TIMEOUT_MESSAGE, token);
                                }else {
                                    String tempTokenId = SaTempUtil.parseToken(token, String.class);
                                    if (!Constants.TEMP_TOKEN_NAME.equals(tempTokenId)) {
                                        throw NotLoginException.newInstance("login", SaTokenConstants.TEMP_INVALID_TOKEN, SaTokenConstants.TEMP_INVALID_TOKEN_MESSAGE, token);
                                    }
                                }
                            } else {
                                throw NotLoginException.newInstance("login", SaTokenConstants.TEMP_NOT_TOKEN, SaTokenConstants.TEMP_NOT_TOKEN_MESSAGE, token);
                            }
                        }
                    }).stop();

            // 登录校验 -- 拦截所有路由
            SaRouter.match("/osfw", "/osfw/**")
                    // 排除指定静态资源文件
                    .notMatch("/osfw/favicon.ico", "/osfw/framework/**/libs/jquery/**", "/osfw/framework/**/libs/blockUI/**", "/osfw/framework/**/libs/modernizr/**", "/osfw/framework/**/libs/amazeui/**", "/osfw/framework/base/common/**", "/osfw/framework/error/**", "/osfw/**/libs/sm2/sm2.js", "/osfw/framework/**/libs/base64/jquery.base64.js", "/osfw/framework/login/vcode/**", "/osfw/framework/login/eraser/**")
                    .check(r -> {
                        if (!StpUtil.isLogin()) {
                            String token = CookieUtils.getCookie(ServletUtils.getRequest(), StpUtil.getTokenName());
                        if (token != null) {
                                StpUtil.setTokenValue(token);
                            }
                        }
                        StpUtil.checkLogin();
                        ServletUtils.getRequest().getMethod();
                    });
        })).addPathPatterns("/osfw/**");

        registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/osfw/**");
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fjc = new FastJsonConfig();
        SerializeConfig serializeConfig = SerializeConfig.globalInstance;
        serializeConfig.put(Long.class , ToStringSerializer.instance);
        serializeConfig.put(Long.TYPE , ToStringSerializer.instance);
        fjc.setSerializeConfig(serializeConfig);
        fastJsonConverter.setFastJsonConfig(fjc);
        converters.add(fastJsonConverter);
    }

}
